﻿@using TamoCRM.Core
@using TamoCRM.Web.Framework.Users
@model TamoCRM.Web.Mvc.Areas.Admin.Models.Contacts.GoFilterModel
@{
    Layout = "~/Areas/Admin/Views/Shared/_Layout.cshtml";
}
@{
    var lstSchools = ViewBag.Schools;
    var lstBranches = ViewBag.Branches;
    var branchSelectList = new SelectList(lstBranches, "BranchId", "Name");
}
<style type="text/css">
    .tblChannel tr th, .tblChannel tr td {
        padding: 3px;
    }

    .tblSchool tr th, .tblSchool tr td {
        padding: 3px;
    }
</style>
<div class="breadcrumbs" id="breadcrumbs">
    <script type="text/javascript">
        try {
            ace.settings.check('breadcrumbs', 'fixed');
        } catch (e) { }
    </script>

    <ul class="breadcrumb">
        <li>
            <i class="icon-home home-icon"></i>
            <a href="/Home">Trang chủ</a>
        </li>

        <li>
            <a href="javascript:void(0);">Danh mục</a>
        </li>
        <li class="active">Contact</li>
    </ul>
</div>

<div class="page-content">
    <div class="page-header">
        <h1>Bàn giao đội lọc		
        </h1>
    </div>
    <!-- /.page-header -->

    <div class="row">
        <div class="form-group">
            <div class="col-sm-12" id="alert">
            </div>
        </div>
        <div class="col-xs-12">
            <div id="spiner"></div>
        </div>
        <div class="col-xs-12">
            <!-- PAGE CONTENT BEGINS -->
            @using (Ajax.BeginForm("GoFilter", "Import", new AjaxOptions { HttpMethod = "POST" }, new { enctype = "multipart/form-data", @class = "form-horizontal", role = "form", id = "gofilterform" }))
            {
                @Html.AntiForgeryToken()
                <div class="form-group">
                    <div class="col-sm-4" id="divSourceTypeCheckbox">
                        @Html.CheckBoxListFor(model => model.PostedSourceTypes.SourceTypeIds, model => model.AllSourceTypes, source => source.SourceTypeId, source => source.Code, model => model.SelectedSourceTypes)
                    </div>
                    <label class="col-sm-0 control-label no-padding-right" for="form-field-2">Ngày nhập từ </label>
                    <div class="col-sm-2" style="font-weight: bold;">
                        @Html.TextBoxFor(model => model.FromDate, new { @required = "required", error = "Từ ngày không được rỗng" })

                    </div>
                    <label class="col-sm-0 control-label no-padding-right" for="form-field-3">Đến</label>
                    <div class="col-sm-2" style="font-weight: bold;">
                        @Html.TextBoxFor(model => model.ToDate, new { @required = "required", error = "Đến ngày không được rỗng" })

                    </div>
                </div>
                <div class="space-4"></div>
                <div class="form-group">
                    <div class="col-sm-8" style="height: 300px; overflow-y: auto; display: block; padding: 0px;">
                        <table border="1" class="table table-striped table-bordered table-hover" style="margin-bottom: 0px;">
                            <thead>
                                <tr>
                                    <td class="col-sm-1" style="font-weight: bold;width: 60px;">Mã</td>
                                    <td class="col-sm-5" style="font-weight: bold">Kênh</td>
                                    <td class="col-sm-1" style="font-weight: bold;width: 60px;">Số lượng</td>
                                    <td class="center col-sm-1" style="font-weight: bold;width: 60px;"><input type="checkbox" id="chkChannels" /></td>
                                </tr>
                            </thead>
                            <tbody id="tbodyChannel">
                                
                            </tbody>
                        </table>
                    </div>
                    <div class="col-sm-4">
                        <table border="1" class="table table-striped table-bordered table-hover" style="margin-bottom: 0px; height: 300px; overflow-y: auto; display: block;">
                            <thead>
                                <tr>
                                    <td class="col-sm-3" style="font-weight: bold">Trường</td>
                                    <td class="center col-sm-1" style="font-weight: bold"><input type="checkbox" id="chkSchools" /></td>
                                </tr>
                            </thead>
                            <tbody id="tbodySchool">
                                @foreach (var school in lstSchools)
                                {
                                    <tr>
                                        <td class="col-sm-3">
                                            <label for="@(school.SchoolId)_chkSchool">@school.Name</label></td>
                                        <td class="col-sm-1 center">
                                            <input type="checkbox" id="@(school.SchoolId)_chkSchool" name="@(school.SchoolId)_chkSchool" value="@(school.SchoolId)" class="chkSchool"/>
                                        </td>
                                    </tr>
                                }
                            </tbody>
                        </table>
                    </div>
                </div>
                <div class="space-4"></div>
                <div class="form-group">
                    <div class="col-sm-4">
                        <label>Tổng số sau khi lọc:</label>
                        <span id="spanFilterCount" style="font-weight: bold;">0</span>
                        <label style="padding-left: 10px;">Số lượng:</label>@Html.TextBoxFor(model => model.Total, new { @style = "width: 40px;" })
                    </div>
                    <div class="col-sm-1" style="width: 9.7%;">
                        Cơ sở đến:
                    </div>
                    <div class="col-sm-2">
                        @Html.DropDownListFor(x => x.BranchId, branchSelectList, new { @width = 90 })
                    </div>
                    <div class="col-sm-2">
                        <button id="btnGoFilter" class="btn-import btn-primary" value="Import">Đưa đội lọc</button>
                    </div>
                </div>
            }


            <table id="grid-table"></table>

            <div id="grid-pager"></div>


            <!-- PAGE CONTENT ENDS -->
        </div>
        <!-- /.col -->
    </div>
    <!-- /.row -->
</div>
<!-- /.page-content -->

<!-- inline scripts related to this page -->
<script id="tmplContact" type="text/x-jquery-tmpl">
    <tr>
        <td></td>
        <td>${Fullname}</td>
        <td>${Address}</td>
        <td>${Email}</td>
    </tr>
</script>
<script type="text/javascript">
    $("#ToDate").datepicker({ format: 'dd/mm/yyyy', autoclose: true });
    $("#FromDate").datepicker({ format: 'dd/mm/yyyy', autoclose: true });
    var curSourceTypeCheck = null;

    $(document).ready(function () {
        $("#BranchId").attr('readonly', 'readonly');
        $("#BranchId").attr('onfocus', 'this.defaultIndex=this.selectedIndex;');
        $("#BranchId").attr('onchange', 'this.selectedIndex=this.defaultIndex;');

        customValidate();
        htmlGlobal = $("#tbodyChannel").html();

        $("#ToDate").change(function (e) {
            e.preventDefault();
            updateChannelCount();
            $("#spanFilterCount").html('0');
        });
        $("#FromDate").change(function (e) {
            e.preventDefault();
            updateChannelCount();
            $("#spanFilterCount").html('0');
        });
        $("#tbodySchool input[type=checkbox]").change(function (e) {
            updateCount();
        });
        $("#tbodyChannel input[type=checkbox]").change(function (e) {
            updateCount();
        });
        $("#divSourceTypeCheckbox input[type=checkbox]").change(function (e) {
            e.preventDefault();
            if ($(this).is(":checked")) {
                if ($(curSourceTypeCheck).val() != $(this).val()) {
                    if (curSourceTypeCheck) $(curSourceTypeCheck).attr('checked', false);
                    curSourceTypeCheck = $(this);
                }
            }
            updateChannelCount();
            $("#spanFilterCount").html('0');
        });

        $("#btnGoFilter").click(function (e) {
            handover();
            return false;
        });
        $('#gofilterform').ajaxForm({
            beforeSend: function () {
                $("#alert").html("<i class='icon-spinner icon-spin orange bigger-125'></i>Đang xử lý...");
            },
            uploadProgress: function (event, position, total, percentComplete) {

            },
            success: function () {

            },
            complete: function (xhr) {
                $("#alert").addClass("alert alert-block alert-success");
                $("#alert").html("Chuyển giao thành công.");
                $('#gofilterform').trigger("reset");
                $("#spanFilterCount").html('0');
            }
        });
        
        $("#chkChannels").click(function () {
            checkAllClassName('chkChannels', 'chkChannel');
            updateCount();
        });
        $("#chkSchools").click(function () {
            checkAllClassName('chkSchools', 'chkSchool');
            updateCount();
        });
    });

    function updateChannelCount() {
        var sourceTypeId = 0;
        var toDate = $("#ToDate").val();
        var fromDate = $("#FromDate").val();
        var statusId = '@((int)StatusType.ImportExcel)';
        var branchId = '@UserContext.GetDefaultBranch()';
        $.each($("#divSourceTypeCheckbox input[type=checkbox]"), function (index) {
            if ($(this).is(':checked'))
                sourceTypeId = $(this).attr("value");
        });
        
        if (sourceTypeId == 0) {
            $("#tbodyChannel").html(htmlGlobal);
            return;
        }
        
        $.each($("#tbodyChannel input[type=checkbox]"), function (index) {
            $(this).attr('checked', false);
        });
        
        $.each($("#tbodySchool input[type=checkbox]"), function (index) {
            $(this).attr('checked', false);
        });

        $.each($("#divSourceTypeCheckbox input[type=checkbox]"), function (index) {
            $(this).attr("disabled", "disabled");
        });
        
        $.get("/admin/api/channel/FilterCountForDistributor", {
            branchId: branchId,
            sourceTypeId: sourceTypeId,
            statusId: statusId,
            from: fromDate,
            to: toDate
        }).done(function (data) {
            $.each($("#divSourceTypeCheckbox input[type=checkbox]"), function (index) {
                $(this).removeAttr("disabled");
            });
            $('#tbodyChannel').html('');
            if (data != null && data.length > 0) {
                var html = '';
                for (var i = 0; i < data.length; i++) {
                    var item = data[i];
                    html += '<tr id="' + item.ChannelId + '_trChannel" name="trChannel">';
                    html += '<td class="col-sm-1" style="width: 60px;">';
                    html += '<label>' + item.Code + '</label>';
                    html += '</td>';
                    html += '<td class="col-sm-5">';
                    html += '<label for="' + item.ChannelId + '_chkChannel">' + item.Name + '</label>';
                    html += '</td>';
                    html += '<td class="col-sm-1" style="width: 60px;">';
                    html += '<label id="' + item.ChannelId + '_lblChannel" name="lblChannel">' + item.Amount + '</label>';
                    html += '</td>';
                    html += '<td class="center col-sm-1" style="width: 60px;">';
                    html += '<input type="checkbox" id="' + item.ChannelId + '_chkChannel" name="' + item.ChannelId + '_chkChannel" value="' + item.ChannelId + '" class="chkChannel"/>';
                    html += '</td>';
                    html += '</tr>';
                }
                $('#tbodyChannel').html(html);
            }
        });

        $('#chkSchools').prop('checked', false);
        $('#chkChannels').prop('checked', false);
    }

    function validateForm() {
        if ($("#FromDate").val() == '') {
            alert("Chưa nhập ngày bắt đầu");
            return false;
        }
        
        if ($("#ToDate").val() == '') {
            alert("Chưa nhập ngày kết thúc");
            return false;
        }
        
        if (parseInt($("#spanFilterCount").html()) < 1) {
            alert("Chưa lọc dữ liệu hoặc không có dữ liệu");
            return false;
        }
        
        var total;
        try {
            total = parseInt($("#Total").val());
            if (total == 0) {
                alert("Số lượng bàn giao không hợp lệ");
                return false;
            }
        }
        catch (err) {
            alert("Số lượng bàn giao không hợp lệ");
            return false;
        }
        
        return true;
    }

    function updateCount() {
        var levelId = 0;
        var statusId = 2;
        var schoolIds = '';
        var channelIds = '';
        var sourceTypeIds = '';
        var toDate = $("#ToDate").val();
        var fromDate = $("#FromDate").val();
        $.each($("#gofilterform input[type=checkbox]"), function (index) {
            var id = $(this).attr("id");
            if (id != 'chkChannels' && id != 'chkSchools') {
                if ($(this).is(':checked')) {
                    var val = $(this).attr("value");
                    if (id.lastIndexOf("PostedSourceTypes") > -1) {
                        sourceTypeIds = sourceTypeIds + val + '|';
                    } else if (id.indexOf("chkChannel") > -1) {
                        var visible = $('#' + val + '_trChannel').is(":visible");
                        if (visible == true) channelIds = channelIds + val + '|';
                    } else if (id.indexOf("chkSchool") > -1) {
                        schoolIds = schoolIds + val + '|';
                    }
                }
            }
        });

        if (sourceTypeIds.length <= 1 || channelIds.length <= 1 || schoolIds.length <= 1) {
            $("#spanFilterCount").html('0');
            return;
        }

        $.post("/admin/api/contact/count", {
            sourceTypeIds: sourceTypeIds,
            channelIds: channelIds,
            schoolIds: schoolIds,
            levelId: levelId,
            statusId: statusId,
            fromDate: fromDate,
            toDate: toDate
        }).done(function (data) {
            $("#spanFilterCount").html(data);
        });
    }

    function handover() {
        var schoolIds = '';
        var channelIds = '';
        var sourceTypeId = 0;
        var toDate = $("#ToDate").val();
        var fromDate = $("#FromDate").val();
        $.each($("#gofilterform input[type=checkbox]"), function (index) {
            var id = $(this).attr("id");
            if (id != 'chkChannels' && id != 'chkSchools') {
                if ($(this).is(':checked')) {
                    var val = $(this).attr("value");
                    if (id.lastIndexOf("PostedSourceTypes") > -1) {
                        if (sourceTypeId == 0) sourceTypeId = val;
                    } else if (id.indexOf("chkChannel") > -1) {
                        var visible = $('#' + val + '_trChannel').is(":visible");
                        if (visible == true) channelIds = channelIds + val + '|';
                    } else if (id.indexOf("chkSchool") > -1) {
                        schoolIds = schoolIds + val + '|';
                    }
                }
            }
        });
        if (sourceTypeId == 0) {
            alertError('Bạn chưa chọn kiểu nguồn để bàn giao');
            return;
        }
        if (channelIds.length <= 1) {
            alertError('Bạn chưa chọn kênh để bàn giao');
            return;
        }
        if (schoolIds.length <= 1) {
            alertError('Bạn chưa chọn trường để bàn giao');
            return;
        }
        var total;
        try {
            total = parseInt($("#Total").val());
            if (total == 0) {
                alertError("Số lượng bàn giao không hợp lệ");
                return;
            }
        }
        catch (err) {
            alertError("Số lượng bàn giao không hợp lệ");
            return;
        }

        alertProcess();
        $.post("/admin/api/contact/HandoverToDistributor", {
            sourceTypeId: sourceTypeId,
            channelIds: channelIds,
            schoolIds: schoolIds,
            fromDate: fromDate,
            toDate: toDate,
            total: total
        }).done(function (data) {
            if (data == '0') 
                alertError("Bàn giao không thành công, vui lòng thử lại");
            else
                alertSuccess("Đã bàn giao thành công");
            
            $('#gofilterform').trigger("reset");
            $("#spanFilterCount").html('0');
            $('#tbodyChannel').html('');
        });
    }
</script>
